# -*- coding: utf-8 -*-
from django.http import HttpResponse, Http404, HttpResponseForbidden
from django.db import models
from django.utils import simplejson
from django.core.validators import ValidationError
from django.core.serializers import serialize
from django.shortcut import get_object_or_404, get_list_or_404
from django.views.generic import list_detail
from models import APIKey
#from datetime import datetime


def get_user(request):
    try:
        # access from key (用key访问)
        return APIKey.objects.get(key=request["_key"]).user
    except (KeyError, ObjectDoesNotExist), e:
        # access from  session (用session访问)
        return request.user


def get_list_or_create(request, app, model):
    if request.method == "GET":
        # 获取列表
        Class = models.get_model(app, model)
        if Class is None:
            raise Http404
        if not get_user(request).has_perm("%s.see_%s"%(app, model)):
            return HttpResponseForbidden('没有查看权限')
        d = {}
        for field in Class._meta.fields:
            try:
                attname = request.GET[field.attname]
            except KeyError:
                pass
            else:
                try:
                    d[field.attname] = field.to_python(attname)
                except ValidationError:
                    # 也可以直接pass
                    response = HttpResponse('参数错误，不能完成请求')
                    response.status_code = 501
                    return response
        result = Class.objects.filter(**d)
        format = request.META.get("ACCEPT", "text/html")
        if format == "application/javascript":
            data = serialize('json', result, ensure_ascii=False)
            return HttpResponse(data, mimetype="application/javascript")
        elif format == "application/xml":
            data = serialize('xml', result, ensure_ascii=False)
            return HttpResponse(data, mimetype="application/xml")
        else:
            return list_detail.object_list(request, result)
    elif request.method == "POST":
        # 创建一条记录
        Class = models.get_model(app, model)
        if Class is None:
            raise Http404
        if not get_user(request).has_perm("%s.add_%s"%(app, model)):
            return HttpResponseForbidden('没有添加权限')
        d = {}
        for field in Class._meta.fields:
            try:
                attname = request.GET[field.attname]
            except KeyError:
                pass
            else:
                try:
                    d[field.attname] = field.to_python(attname)
                except ValidationError:
                    response = HttpResponse('参数错误，不能完成请求')
                    response.status_code = 501
                    return response
        try:
            Class.objects.create(**d)
        except:
            response = HttpResponse('参数错误，不能完成请求')
            response.status_code = 501
            return response
        return HttpResponse('成功添加一条记录')


def rud(request, app, model, pk):
    # read, update, delete 操作
    if request.method == "GET":
        func = "read"
    elif request.method == "POST":
        method = request.POST.get("_method", "").upper() # prototype风格
        if method == "PUT":
            func = "update"
        elif method == "DELETE":
            func = "delete"
        else:
            raise Http404
    elif request.method == "PUT":
        func = "update"
    elif request.method == "DELETE":
        func = "delete"
    else:
        raise Http404
    return globals()[func](request, app, model, pk)


def read(request, app, model, pk):
    Class = models.get_model(app, model)
    if Class is None:
        raise Http404
    # 需要自己在models.py中设置查看权限
    # e.g. permissions = (("see_termindex", "Can see TermIndex"))
    if not get_user(request).has_perm("%s.see_%s"%(app, model)):
        return HttpResponseForbidden('没有查看权限')
    # 为了方便返回了一个长度为1的list, 如何序列化一个对象而不是query_set?
    result = get_list_or_404(Class, pk=pk)
    # 根据 request header 判断
    format = request.META.get("ACCEPT", "text/html")
    if format == "application/javascript":
        data = serialize('json', result, ensure_ascii=False)
        return HttpResponse(data, mimetype="application/javascript")
    elif format == "application/xml":
        data = serialize('xml', result, ensure_ascii=False)
        return HttpResponse(data, mimetype="application/xml")
    else:
        return list_detail.object_detail(request, result[0])


def update(request, app, model, pk):
    Class = models.get_model(app, model)
    if Class is None:
        raise Http404
    if not get_user(request).has_perm("%s.change_%s"%(app, model)):
        return HttpResponseForbidden('没有修改权限')

    obj = get_object_or_404(Class, pk=pk)
    for field in obj._meta.fields:
        try:
            value = request.POST[field.attname]
        except KeyError:
            pass
        else:
            try:
                setattr(obj, field.attname, field.to_python(value))
            except ValidationError:
                response = HttpResponse('参数错误，不能完成请求')
                response.status_code = 501
                return response
# 同步设置当前修改时间和用户
#    obj.update_time = datetime.today()
#    obj.update_user = get_user(request)
    obj.save()
    return HttpResponse('修改成功')


def delete(request, app, model, pk):
    Class = models.get_model(app, model)
    if Class is None:
        raise Http404
    if not get_user(request).has_perm("%s.delete_%s"%(app, model)):
        return HttpResponseForbidden('没有删除权限')
    get_object_or_404(Class, pk=pk).delete()
    return HttpResponse('删除成功')
